/*
 * @Author: fengxx
 * @Date: 2025-08-19 14:05:40
 * @LastEditors: fengxx
 * @LastEditTime: 2025-08-19 19:46:54
 */

// const arr = Array.from({ length: 101 }, (_, index) => index + 1);
let newArr = [];
for (let i = 0; i < 101; i++) {
  newArr.push(i + 1);
}
// console.log(newArr);

let current = 1;
let pageSize = 10;
let pageSizeArr = [10, 50, 100];
let pageTotal = Math.ceil(newArr.length / pageSize);
const pageWrap = document.getElementById("page-wrap");

function showList() {
  const listWrap = document.getElementById("list-wrap");
  listWrap.innerHTML = "";
  const start = (current - 1) * pageSize;
  const end = current * pageSize - 1;
  let arr = newArr.filter((item, index) => index >= start && index <= end);
  arr.forEach((item) => {
    listWrap.innerHTML += `<li>列表数据${item}</li>`;
  });
}

function showPage() {
  let str = `<li>共${newArr.length}条</li><li class="page-btn">上一页</li>`;

  for (let i = 0; i < pageTotal; i++) {
    const activeCls = i + 1 == current ? "active" : "";
    str += `<li class="page-btn ${activeCls}">${i + 1}</li>`;
  }

  str += `<li class="page-btn">下一页</li><li><select name="" id="size-wrap">`;

  pageSizeArr.forEach((item) => {
    str += `<option value="${item}">${item}条/页</option>`;
  });

  str += `</select></li><li style="margin-left: 5px">跳至<input type="number" id="jump-page" style="width: 60px">页</li>`;

  pageWrap.innerHTML = str;
}

showList();
showPage();

pageWrap.addEventListener("click", function (e) {
  if (e.target.classList.contains("page-btn")) {
    if (e.target.innerHTML == "上一页") {
      if (current <= 1) {
        return;
      }
      current--;
    } else if (e.target.innerHTML == "下一页") {
      if (current >= pageTotal) {
        return;
      }
      current++;
    } else {
      current = e.target.innerHTML;
    }
    showList();
    showPage();
  }
});

pageWrap.addEventListener("change", function (e) {
  if (e.target.id == "size-wrap") {
    current = 1;
    pageSize = e.target.value;
    pageTotal = Math.ceil(newArr.length / pageSize);
    showList();
    showPage();
    const options = document.querySelectorAll("#size-wrap option");

    for (let i = 0; i < options.length; i++) {
      options[i].removeAttribute("selected");
      if (options[i].value == pageSize) {
        options[i].setAttribute("selected", true);
      }
    }
  }
});

document.addEventListener("keydown", function (e) {
  if (e.key == "Enter") {
    const jumpPage = document.getElementById("jump-page").value || 1;
    if (jumpPage < 1) {
      current = 1;
    } else if (jumpPage > pageTotal) {
      current = pageTotal;
    } else {
      current = jumpPage;
    }
    showList();
    showPage();
  }
});
